package mk.com.it.android;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import android.content.Context;

public class WebFeeds {

	InputStream inputStream;
	List<RssPost> posts;
	String urlAddress;

	public WebFeeds(String urlAddress) {
		this.urlAddress = urlAddress;
	}

	private void getFromURL(String urlAddress)
			throws ParserConfigurationException, SAXException, IOException {
		// Get the XML
		URL url;
		try {
			url = new URL(urlAddress);

			URLConnection connection;

			connection = url.openConnection();

			HttpURLConnection httpConnection = (HttpURLConnection) connection;
			int responseCode = httpConnection.getResponseCode();

			if (responseCode == HttpURLConnection.HTTP_OK) {
				InputStream in = httpConnection.getInputStream();
				posts = RssParser.readXml(in);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}

	private void getLocalTest(Context c) throws ParserConfigurationException,
			SAXException, IOException {
		InputStream in = c.getResources().openRawResource(R.raw.feed);
		posts = RssParser.readXml(in);
		
	}

	public List<RssPost> getLatestFeed(Context c) {
		posts = new ArrayList<RssPost>();

		try {
			try {
				getFromURL(urlAddress);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				try {
					getLocalTest(c);
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return posts;
	}
}
